package app.android.alampang.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import app.android.alampang.model.Note;
import app.android.alampang.ui.core.BaseActivity;
import app.android.alampang.R;
import app.android.alampang.ui.custom.FloatingActionButton;
import app.android.alampang.utility.DatabaseHandler;
import app.android.alampang.utility.NavigationService;

import static android.view.View.OnClickListener;

/**
 * Created by Lihong on 12/02/2015.
 */
public class CreateNoteActivity extends BaseActivity implements OnClickListener
{

    private View btn_image;
    private final int REQUEST_PHOTO_CODE = 69;
    private ImageView pic;
    private String mCurrentPhotoPath;

    private EditText inTitle;
    private EditText inDesc;
    private FloatingActionButton btnSave;
    private FloatingActionButton btnRemove;
    private FloatingActionButton btnShare;

    private boolean isEditMode = false;

    private Note note;

    @Override
    public void onCreate(Bundle savedInstanceState, Bundle param)
    {
        setContentView(R.layout.activity_create_note);
        if (param != null) {
            isEditMode = true;
            note = new Note();
            note.parseFromJSONString(param.getString(Note.PARSING_NAME));
        }
    }

    @Override
    public void initialize()
    {
        pic = (ImageView) findViewById(R.id.pic);
        btn_image = findViewById(R.id.btn_image);
        btn_image.setOnClickListener(this);

        btnSave = (FloatingActionButton) findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this);

        btnRemove = (FloatingActionButton) findViewById(R.id.btn_remove);
        btnRemove.setOnClickListener(this);


        btnShare = (FloatingActionButton) findViewById(R.id.btn_share);
        btnShare.setOnClickListener(this);

        inTitle = (EditText) findViewById(R.id.input_title);
        inDesc = (EditText) findViewById(R.id.input_description);

    }

    @Override
    public void onLock() {

    }

    @Override
    public void onUnLock() {
        if (isEditMode)
        {
            btnRemove.setVisibility(View.VISIBLE);
            btnShare.setVisibility(View.VISIBLE);

            inTitle.setText(note.getName());
            inDesc.setText(note.getDescription());

            btn_image.setVisibility(View.GONE);
            try {
                setPic();
            }
            catch (Exception e)
            {
                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("รูปถ่ายไม่สมบูรณ์")
                        .setMessage("ต้องการลบภาพนี้หรือไม่")
                        .setPositiveButton("ใช่", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                DatabaseHandler db = new DatabaseHandler(CreateNoteActivity.this);
                                db.delete(note);

                                NavigationService.getInstance().navigate(CreateNoteActivity.this, NotesActivity.class, true);
                            }

                        })
                        .setNegativeButton("ยกเลิก", null)
                        .show();
            }
        }
        else
        {
            btnRemove.setVisibility(View.GONE);
            btnShare.setVisibility(View.GONE);
        }

    }

    @Override
    public void onReset() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_PHOTO_CODE) && (resultCode == RESULT_OK))
        {
            btn_image.setVisibility(View.INVISIBLE);
            setPic();
        }
    }

    private File createImageFile() throws IOException
    {
        String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
        String imageFileName = "Alampang-" + timeStamp + "-";
        File storageDir = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Alampang");
        File image;
        if (!storageDir.exists())
        {
            storageDir.mkdirs();
            image = File.createTempFile(imageFileName, ".jpg", storageDir);
        }
        else
        {
            image = File.createTempFile(imageFileName, ".jpg", storageDir);
        }

        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void setPic()
    {
        if (isEditMode)
        {
            if (note.getImageUri().isEmpty()) return;

            try {
                Bitmap bmp = BitmapFactory.decodeFile(note.getImageUri());
                pic.setImageBitmap(bmp);
                pic.setVisibility(View.VISIBLE);
            }
            catch (Exception e)
            {

            }
        }
        else
        {
            int targetW = btn_image.getWidth();
            int targetH = btn_image.getHeight();

            // scale
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
            int photoW = bmOptions.outWidth;
            int photoH = bmOptions.outHeight;
            int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = scaleFactor;
            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

            // check orientation
            ExifInterface exif = null;
            try
            {
                exif = new ExifInterface(mCurrentPhotoPath);
            }
            catch (IOException e)
            {
                Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
            }
            int orientation = 6;
            if (exif != null)
            {
                orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
            }

            Matrix matrix = new Matrix();
            if (orientation == 6)
            {
                matrix.postRotate(90);
            }
            else if (orientation == 3)
            {
                matrix.postRotate(180);
            }
            else if (orientation == 8)
            {
                matrix.postRotate(270);
            }

            Bitmap pBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            pic.setImageBitmap(pBitmap);
            pic.setVisibility(View.VISIBLE);
        }
    }

    private void galleryAddPic()
    {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void saveNote()
    {
        String name = inTitle.getText().toString();
        String desc = inDesc.getText().toString();

        if (name.isEmpty() || desc.isEmpty() || mCurrentPhotoPath.isEmpty())
        {
            Toast.makeText(this, "กรุณากรอกข้อมูลให้ครบ", Toast.LENGTH_LONG).show();
            return;
        }

        try
        {
            DatabaseHandler db = new DatabaseHandler(this.getApplicationContext());
            Note note = new Note();
            note.setImageUri(mCurrentPhotoPath);
            note.setDescription(desc);
            note.setName(name);

            db.insert(note);
            db.close();
            galleryAddPic();
            Toast.makeText(this, "บันทึกสำเร็จ", Toast.LENGTH_LONG).show();

            NavigationService.getInstance()
                    .navigate(this, NotesActivity.class, true);
        }
        catch (Exception e)
        {
            Toast.makeText(this, "บันทึกข้อมูลไม่สำเร็จ", Toast.LENGTH_LONG).show();
        }

    }

    private void removeNote()
    {

        if (note != null)
        {
            try
            {
                DatabaseHandler db = new DatabaseHandler(this);

                db.delete(note);

                Toast.makeText(this, "ลบบันทึกสำเร็จ", Toast.LENGTH_LONG).show();
                NavigationService.getInstance()
                        .navigate(this, NotesActivity.class, true);
            }
            catch (Exception e)
            {
                Toast.makeText(this, "ลบบันทึกไม่สำเร็จ", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void editNote()
    {
        String name = inTitle.getText().toString();
        String desc = inDesc.getText().toString();

        if (name.isEmpty() || desc.isEmpty())
        {
            Toast.makeText(this, "กรุณากรอกข้อมูลให้ครบ", Toast.LENGTH_LONG).show();
            return;
        }

        try
        {
            DatabaseHandler db = new DatabaseHandler(this);

            note.setName(name);
            note.setDescription(desc);

            db.update(note);

            Toast.makeText(this, "บันทึกสำเร็จ", Toast.LENGTH_LONG).show();
            NavigationService.getInstance()
                    .navigate(this, NotesActivity.class, true);
        }
        catch (Exception e)
        {
            Toast.makeText(this, "บันทึกข้อมูลไม่สำเร็จ", Toast.LENGTH_LONG).show();
        }
    }

    private void lunchCamApp()
    {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            File photoFile = null;
            try
            {
                photoFile = createImageFile();
            }
            catch (IOException ex)
            {
                Toast.makeText(CreateNoteActivity.this, ex.toString(), Toast.LENGTH_LONG).show();
            }

            if (photoFile != null)
            {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_PHOTO_CODE);
            }
        }
    }

    private void shareNote()
    {
        Intent share = new Intent(Intent.ACTION_SEND);

        share.setType("image/*");

        String imagePath = note.getImageUri();

        File imageFile = new File(imagePath);
        Uri uri = Uri.fromFile(imageFile);

        share.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(share, "Share this photo to ..."));
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_remove:
                removeNote();
                break;
            case R.id.btn_save:
                if (isEditMode) editNote();
                else saveNote();
                break;
            case R.id.btn_share:
                shareNote();
                break;
            case R.id.btn_image:
                if (isEditMode) return;
                lunchCamApp();
                break;
        }
    }
}
